package com.jsz.peini.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.base.SerializeUtil;

public class ShieldTextFiltration {
	private static Map<Character, List<String>> wordListToMap(
			List<String> sensitiveWordList) {
		Map<Character, List<String>> result = new HashMap<Character, List<String>>();
		for (String s : sensitiveWordList) {
			char c = s.charAt(0);
			List<String> strs = result.get(c);
			if (strs == null) {
				strs = new ArrayList<String>();
				result.put(c, strs);
			}
			strs.add(s);
		}

		return result;
	}

	public static String filter(String src) {
		//拿取屏蔽字库信息
		List<String> sensitiveWordList=null;
		List<byte[]> ll = RedisUtil.lrange(RedisConstants.SHIED_TEXT.getBytes(), 0, RedisUtil.llen(RedisConstants.SHIED_TEXT.getBytes()));
		for (byte[] bs : ll) {
			sensitiveWordList= (List<String>)SerializeUtil.unserialize(bs);
		}
		Map<Character, List<String>> wordMap = wordListToMap(sensitiveWordList);
		StringBuilder strb = new StringBuilder();
		for (int i = 0; i < src.length(); i++) {
			char c = src.charAt(i);
			String find = null;
			if (wordMap.containsKey(c)) {
				List<String> words = wordMap.get(c);
				for (String s : words) {
					String temp = src.substring(i,
							(s.length() <= (src.length() - i)) ? i + s.length()
									: i);
					if (s.equals(temp)) {
						find = s;
						break;
					}
				}
			}
			if (find != null) {
				strb.append("***");
				i += (find.length() - 1);
			} else {
				strb.append(c);
			}
		}
		return strb.toString();
	}
}
